package com.java.controller;

import com.java.entity.Answer;
import com.java.service.AnswerService;
import com.java.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class AnswerController extends BaseController {

    @Autowired
    private AnswerService answerService;

    @PostMapping("answer/insert")
    public ResultVo insert(@RequestBody Answer answer) {
        int rows = answerService.insert(answer);
        return toVo(rows);
    }

    @PostMapping("answer/insertBatch")
    public ResultVo insertBatch(@RequestBody Map<String, Object> map) {
        Integer paperId = (Integer) map.remove("paperId");

        List<Answer> answers = new ArrayList<>();
        map.forEach((questionId, answer) -> {
            Answer a = new Answer();
            a.setPaperId(paperId);
            a.setQuestionId(Integer.parseInt(questionId));
            if (answer instanceof Integer) {
                a.setAnswerQuestionOptionId((Integer) answer);
            } else {
                a.setAnswerText((String) answer);
            }
            answers.add(a);
        });

        answerService.insertBatch(answers);
        return ResultVo.success();
    }

    @PostMapping("answer/delete")
    public ResultVo delete(@RequestBody String answerId) {
        if (!StringUtils.hasText(answerId)) {
            throw new RuntimeException("answerId is null");
        }
        int rows = answerService.delete(Integer.valueOf(answerId));
        return toVo(rows);
    }

    @PostMapping("answer/update")
    public ResultVo update(@RequestBody Answer answer) {
        int rows = answerService.update(answer);
        return toVo(rows);
    }

    @PostMapping("answer/selectOne")
    public ResultVo selectOne(@RequestBody String answerId) {
        if (!StringUtils.hasText(answerId)) {
            throw new RuntimeException("answerId is null");
        }
        Answer answer = answerService.selectOne(Integer.valueOf(answerId));
        return ResultVo.success(answer);
    }

    @PostMapping("answer/selectAll")
    public ResultVo selectAll() {
        List<Answer> list = answerService.selectAll();
        return ResultVo.success(list);
    }

}
